package com.cx.mall.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.cx.mall.common.entity.user.entity.UserInfo;
import com.cx.mall.common.util.JWTUtils;
import com.cx.mall.common.util.ResponseEnum;
import com.cx.mall.common.util.ResponseVo;
import com.cx.mall.user.mapper.UserInfoMapper;
import com.cx.mall.user.mapper.UserReceiveAddressMapper;
import com.cx.mall.user.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2025-08-07
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserReceiveAddressMapper userReceiveAddressMapper;

    @Override
    public ResponseVo<UserInfo> register(UserInfo userInfo) {
        QueryChainWrapper<UserInfo> chainWrapper = new QueryChainWrapper<>(baseMapper);
        // 1. 校验用户名是否存在
        UserInfo userInfo1 = chainWrapper.eq("username", userInfo.getUsername()).one();
        if(userInfo1 != null){
            return ResponseVo.fail(ResponseEnum.USER_HAS_EXISTED);
        }
        // 2. 校验邮箱是否存在
        UserInfo userInfo2 = chainWrapper.eq("email", userInfo.getEmail()).one();
        if(userInfo2 != null){
            throw new RuntimeException("邮箱已存在");
        }
        userInfo.setPassword(BCrypt.hashpw(userInfo.getPassword(), BCrypt.gensalt()));
        userInfoMapper.insert(userInfo);
        return ResponseVo.success();

    }

    @Override
    public UserInfo login(String username, String password) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUsername, username);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if(userInfo == null){
            throw new RuntimeException("用户名不存在");
        }
        if(!BCrypt.checkpw(password, userInfo.getPassword())){
            throw new RuntimeException("密码错误");
        }
        return userInfo;
    }
}
